package com.qtjf.qtmoneyservice.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.qtjf.qtmoneyservice.R;
import com.qtjf.qtmoneyservice.constantSet.Constant;
import com.qtjf.qtmoneyservice.view.ShenFenRenGongView;
import com.qtjf.qtmoneyservice.view.ShenFenZidongView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ShenFenActivity extends BaseActivity {

    ImageView mBack;
    TextView submitBt;
    ViewPager viewPager;
    List<View> lists;
    MyViewPagerAdapter adapter;
    TextView ziDongBt;
    TextView renGongBt;
    ShenFenZidongView ziDongView;
    ShenFenRenGongView shouDongView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shen_fen);

        super.setTranslucent();
        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mBack = (ImageView) findViewById(R.id.back_bt);

        submitBt= (TextView) findViewById(R.id.submit_bt);
        viewPager= (ViewPager) findViewById(R.id.viewpager);
        ziDongBt= (TextView) findViewById(R.id.zidong_bt);
        renGongBt= (TextView) findViewById(R.id.rengong_bt);
        ziDongView=new ShenFenZidongView(this);
        shouDongView=new ShenFenRenGongView(this);

    }

    private void initData() {
        lists=new ArrayList<View>();
        lists.add(ziDongView.getView());
        lists.add(shouDongView.getView());
        adapter=new MyViewPagerAdapter();
        viewPager.setAdapter(adapter);

    }

    private void initEvent() {
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShenFenActivity.this.finish();
            }
        });

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                if(position==0)
                {
                    ziDongBt.setTextColor(Color.parseColor("#ffffff"));
                    ziDongBt.setBackgroundResource(R.drawable.rengong_press_bg);

                    renGongBt.setTextColor(Color.parseColor("#4162ff"));
                    renGongBt.setBackgroundResource(R.drawable.zidong_normal_bg);
                }else{
                    ziDongBt.setTextColor(Color.parseColor("#4162ff"));
                    ziDongBt.setBackgroundResource(R.drawable.rengong_normal_bg);

                    renGongBt.setTextColor(Color.parseColor("#ffffff"));
                    renGongBt.setBackgroundResource(R.drawable.zidong_press_bg);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        ziDongBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ziDongBt.setTextColor(Color.parseColor("#ffffff"));
                ziDongBt.setBackgroundResource(R.drawable.rengong_press_bg);

                renGongBt.setTextColor(Color.parseColor("#4162ff"));
                renGongBt.setBackgroundResource(R.drawable.zidong_normal_bg);
                viewPager.setCurrentItem(0);
            }
        });

        renGongBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ziDongBt.setTextColor(Color.parseColor("#4162ff"));
                ziDongBt.setBackgroundResource(R.drawable.rengong_normal_bg);

                renGongBt.setTextColor(Color.parseColor("#ffffff"));
                renGongBt.setBackgroundResource(R.drawable.zidong_press_bg);
                viewPager.setCurrentItem(1);
            }
        });

    }

    class MyViewPagerAdapter extends PagerAdapter
    {

        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(lists.get(position));
            return lists.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            container.removeView(lists.get(position));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==RESULT_OK )
        {
            switch(requestCode)
            {
                case 1:
                    File f=new File(Environment.getExternalStorageDirectory()
                            +"/"+"imgs"+"/"+"imgs1.jpg");
                    try {
                        Uri u =
                                Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                                        f.getAbsolutePath(), null, null));
                        //u就是拍摄获得的原始图片的uri，剩下的你想干神马坏事请便……
                        shouDongView.setImage1(decodeUri(ShenFenActivity.this,u, Constant.getSCREENWIDTH(),Constant.getSCREENHEIGHT()));

                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    File f1=new File(Environment.getExternalStorageDirectory()
                            +"/"+"imgs"+"/"+"imgs1.jpg");
                    try {
                        Uri u =
                                Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                                        f1.getAbsolutePath(), null, null));
                        //u就是拍摄获得的原始图片的uri，剩下的你想干神马坏事请便……
                        shouDongView.setImage2(decodeUri(ShenFenActivity.this,u, Constant.getSCREENWIDTH(),Constant.getSCREENHEIGHT()));

                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }



    /**
     * 读取一个缩放后的图片，限定图片大小，避免OOM
     * @param uri       图片uri，支持“file://”、“content://”
     * @param maxWidth  最大允许宽度
     * @param maxHeight 最大允许高度
     * @return  返回一个缩放后的Bitmap，失败则返回null
     */
    public static Bitmap decodeUri(Context context, Uri uri, int maxWidth, int maxHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; //只读取图片尺寸
        resolveUri(context, uri, options);

        //计算实际缩放比例
        int scale = 1;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            if ((options.outWidth / scale > maxWidth &&
                    options.outWidth / scale > maxWidth * 1.4) ||
                    (options.outHeight / scale > maxHeight &&
                            options.outHeight / scale > maxHeight * 1.4)) {
                scale++;
            } else {
                break;
            }
        }

        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;//读取图片内容
        options.inPreferredConfig = Bitmap.Config.RGB_565; //根据情况进行修改
        Bitmap bitmap = null;
        try {
            bitmap = resolveUriForBitmap(context, uri, options);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    private static void resolveUri(Context context, Uri uri, BitmapFactory.Options options) {
        if (uri == null) {
            return;
        }

        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
                ContentResolver.SCHEME_FILE.equals(scheme)) {
            InputStream stream = null;
            try {
                stream = context.getContentResolver().openInputStream(uri);
                BitmapFactory.decodeStream(stream, null, options);
            } catch (Exception e) {
                Log.w("resolveUri", "Unable to open content: " + uri, e);
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        Log.w("resolveUri", "Unable to close content: " + uri, e);
                    }
                }
            }
        } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
            Log.w("resolveUri", "Unable to close content: " + uri);
        } else {
            Log.w("resolveUri", "Unable to close content: " + uri);
        }
    }

    private static Bitmap resolveUriForBitmap(Context context, Uri uri, BitmapFactory.Options options) {
        if (uri == null) {
            return null;
        }

        Bitmap bitmap = null;
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
                ContentResolver.SCHEME_FILE.equals(scheme)) {
            InputStream stream = null;
            try {
                stream = context.getContentResolver().openInputStream(uri);
                bitmap = BitmapFactory.decodeStream(stream, null, options);
            } catch (Exception e) {
                Log.w("resolveUriForBitmap", "Unable to open content: " + uri, e);
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        Log.w("resolveUriForBitmap", "Unable to close content: " + uri, e);
                    }
                }
            }
        } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
            Log.w("resolveUriForBitmap", "Unable to close content: " + uri);
        } else {
            Log.w("resolveUriForBitmap", "Unable to close content: " + uri);
        }

        return bitmap;
    }
}
